package com.heima.wemedia.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.contatns.ScheduleConstants;
import com.heima.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemeida.pojos.WmNews;
import com.heima.task.feign.TaskFeign;
import com.heima.utils.common.JsonUtils;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 每秒定时扫描延迟队列，定时发布文章
 */
@Component
@Slf4j
public class WmNewsTaskJob {
    @Autowired
    private TaskFeign taskFeign;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 每秒执行的任务
     * fixedRate: 固定频率（毫秒）
     */
    @Scheduled(fixedRate = 1000)
    public void publishWmNews(){
        //到延迟任务获取到期的任务
        ResponseResult<List<Task>> responseResult = taskFeign.pollTask(ScheduleConstants.TASK_TOPIC_NEWS_PUBLISH);

        if(responseResult.getCode().equals(200)){
            List<Task> taskList = responseResult.getData();

            if(CollectionUtils.isNotEmpty(taskList)){
                List<Integer> ids  = new ArrayList<>();

                taskList.forEach(task -> {
                    String wmNewsJson = task.getParameters();
                    WmNews wmNews = JsonUtils.toBean(wmNewsJson, WmNews.class);

                    //根据id查询文章
                    wmNews = wmNewsMapper.selectById(wmNews.getId());

                    //发表文章
                    wmNewsAutoScanService.saveApArticle(wmNews);

                    ids.add(wmNews.getId());
                });

                log.info("文章已经完成定时发布 {} id :",ids);
            }
        }
    }
}
